
//添加事件
function getEvent() {
    document.getElementById('activeBtn').addEventListener("click", function () {
        window.location.href = `./homePage.html`;
    });
    document.getElementById('searchBtn').addEventListener("click", function () {
        searchData()
    });
}
function searchData() {
    let content = document.getElementById('contact')
    let articleContent = document.getElementById('articleContent')
    document.getElementById('dutyList').style.display = 'none';
    content.style.display = 'block'
    articleContent.style.display = 'none'
    let val = document.getElementById('myInput').value;
    queryPageList(1, 10, val)
}
function queryWeek() {
    ajax('GET', `portalWebsite/homepage/queryWeek`, null, function (res) {
        var { data } = res;
        var list = data || []
        var domStr = ''
        var dutyListInfo = document.getElementById('dutyListInfo')
        ajax('GET', 'portalWebsite/homepage/queryEndPage', null, function (res) {
            endData = res.data || {}
            list.forEach(e => {
                domStr += `<div class="info">
                        <div class="time">${e.dutyDate}</div>
                        <div class="person"><span>${endData.dutyOne || '值班领导'}</span>${e.leader}</div>
                        <div class="person"><span>${endData.dutyTwo || '值班人员'}</span>${e.officer}</div>
                        <div class="person"><span>${endData.dutyThree || '值班驾驶员'}</span>${e.driver}</div>
                    </div>`
            })
            dutyListInfo.innerHTML = domStr
        })
    })
}
function queryPageList(page, size, searchLabel) {
    ajax('GET', `portalWebsite/article/queryPageList?page=${page}&size=${size}&searchStr=${searchLabel}`, null, function (res) {
        var { data } = res;
        let list = data ? data.list || [] : [];
        let totalPage = data.totalPage || 1;
        let articleInfoList = document.getElementById(`articleInfoList`);
        let htmlStr = ''
        list.forEach((e, index) => {
            let domStr = `<div class="title jumpArticle" data-id='${e.articleId}'><span class="text"><span>▤</span> ${e.title}</span><span
                                class="time">${e.publishTime}</span></div>`
            htmlStr += domStr
        })
        if (!list || !list.length) {
            articleInfoList.innerHTML = "<div class='noData'>暂无相关资讯</div>"
        } else {
            articleInfoList.innerHTML = htmlStr
        }
        document.getElementById('articleType').style.display = 'none';
        document.getElementById('articleInfo').style.width = '100%';
        var pagercontainer = document.getElementById('pagercontainer');
        pagercontainer.style.display = 'block'
        isSearchArticle = false;
        createPager(page, totalPage, 5, pagercontainer);
        setTimeout(() => {
            addClickEvent()
        }, 1000)
    })
}
function searchParams() {
    const url = new URL(window.location.href);
    navigationId = url.searchParams.get('navigationId');
    var searchStr = url.searchParams.get('searchStr');
    var articleId = url.searchParams.get('articleId');
    var duty = url.searchParams.get('duty');
    let content = document.getElementById('contact')
    let articleContent = document.getElementById('articleContent')
    let dutyList = document.getElementById('dutyList')
    content.style.display = 'block'
    articleContent.style.display = 'none'
    dutyList.style.display = 'none'
    if (navigationId) {
        setTimeout(() => {
            queryByNavigationId(navigationId);
        }, 100)
    } else if (articleId) {
        // console.log(articleId)
        content.style.display = 'none'
        articleContent.style.display = 'block'
        ajax('GET', `portalWebsite/article/query?articleId=${articleId}`, null, function (res) {
            let { data } = res;
            if (data.jumpType == 'URL' && data.url) {
                jumpArticle(data)
            } else {
                setArticleData(data)
            }
        })
    } else if (duty) {
        content.style.display = 'none'
        articleContent.style.display = 'none'
        dutyList.style.display = 'block'
    } else {
        document.getElementById('myInput').value = searchStr;
        queryPageList(1, 10, searchStr)
    }
}
function createPager(pager, pagerNumber, middlePager, container) {
    // 清空
    container.innerText = '';
    var divpager = document.createElement('div');
    pager.className = 'pager';
    /*
     * className:样式类
     * text:中间的显示文本
     * newPager: 点击后跳转到哪一页
     */
    function createAnchor(className, text, newPager) {
        var a = document.createElement('a');
        a.className = className;
        a.innerText = text;
        divpager.appendChild(a);
        a.onclick = function () {
            // 做相应的三种情况的判断
            //console.log(newPager, pagerNumber, middlePager, container)
            if (!isSearchArticle) {
                let val = document.getElementById('myInput').value;
                queryPageList(newPager, 10, val)
            } else {
                // console.log(newPager, pagerNumber, middlePager, container)
                articlePage = newPager;
                createArticleInfo()
            }
            if (newPager < 1 || newPager > pagerNumber || newPager === pager) {
                return;
            }
            createPager(newPager, pagerNumber, middlePager, container);
            addClickEvent()
            setTimeout(() => {
                addClickEvent()
            }, 1000)
        }
    }
    // 首页和上一页
    if (pager === 1) {
        createAnchor('disabled', '首页', 1)
        createAnchor('disabled', '上一页', pager - 1)
    } else {
        createAnchor('', '首页', 1)
        createAnchor('', '上一页', pager - 1)
    }
    // 中间的数字
    var min = Math.floor(pager - middlePager / 2);
    if (min < 1) {
        min = 1;
    }
    var max = min + middlePager - 1;
    if (max > pagerNumber) {
        max = pagerNumber;
    }
    for (var i = min; i <= max; i++) {
        if (i === pager) {
            createAnchor('active', i, i);
        } else {
            createAnchor('', i, i);
        }
    }
    // 下一页和尾页
    if (pager === pagerNumber) {
        createAnchor('disabled', '下一页', pager + 1)
        createAnchor('disabled', '尾页', pagerNumber);
    } else {
        createAnchor('', '下一页', pager + 1)
        createAnchor('', '尾页', pagerNumber);
    }
    // 当前页
    var span = document.createElement('span');
    span.innerText = pager + "/" + pagerNumber;
    divpager.appendChild(span);
    // 添加进容器中
    container.appendChild(divpager);
}
function queryNavigation() {
    ajax('GET', 'portalWebsite/homepage/queryNavigation', null, function (res) {
        var { data } = res
        let articleTypeList = document.getElementById('articleTypeList')
        let domStr = ''
        navigation = data || []
        navigation.forEach(e => {
            domStr += ` <div class="item articleTypeBtn" data-id='${e.navigationId}'>
                            <div class="text">${e.navigationName}</div>
                        </div>`
        })
        articleTypeList.innerHTML = domStr;
        let articleTypeBtnList = document.querySelectorAll('.articleTypeBtn')
        Array.from(articleTypeBtnList).forEach(e => {
            e.addEventListener("click", function () {
                queryByNavigationId(e.getAttribute('data-id'))
            });

        })
    })
}
//文章类型分类
let articleList = [];
let articlePage = 1;
let isSearchArticle = true;
function queryByNavigationId(id) {
    document.getElementById('contact').style.display = 'block';
    document.getElementById('articleContent').style.display = 'none';
    document.getElementById('dutyList').style.display = 'none';
    ajax('GET', `portalWebsite/homepage/queryByNavigationId?navigationId=${id}`, null, function (res) {
        let { data } = res;
        data = data || [];
        articleList = data;
        isSearchArticle = true;
        document.getElementById('articleType').style.display = 'block';
        let tagList = document.querySelectorAll('.tagBtn');
        let articleTypeBtnList = document.querySelectorAll('.articleTypeBtn');
        let rutTag = navList.find(e => e.navigationId == id)
        let rutArticleType = navigation.find(e => e.navigationId == id)
        if (rutTag) {
            Array.from(tagList).forEach(e => {
                e.className = 'tag tagBtn newTag'
                if (e.textContent.includes(rutTag.navigationName)) {
                    e.id = 'activeBtn'
                    e.style.backgroundColor = endData.hoverColor || '#137bff';
                } else {
                    e.style.backgroundColor = '#00000000';
                    e.id = ''
                }
            })
        }
        if (rutArticleType) {
            Array.from(articleTypeBtnList).forEach(e => {
                //console.log(id, e.getAttribute('data-id'))
                if (e.textContent.includes(rutArticleType.navigationName)) {
                    e.className = 'item articleTypeBtn activeType'
                } else {
                    e.className = 'item articleTypeBtn'
                }
            })
        }
        document.getElementById('articleInfo').style.width = 'calc(100% - 320px)';
        createArticleInfo()
        addClickEvent()
    })
}
function createArticleInfo() {
    let newArticleList = []
    let data = [];
    for (let i = 0; i < articleList.length; i += 10) {
        newArticleList.push(articleList.slice(i, i + 10));
    }
    data = newArticleList[articlePage - 1] || [];
    let articleInfoList = document.getElementById(`articleInfoList`);
    let htmlStr = '';
    data.forEach((e, index) => {
        let domStr = `<div class="title jumpArticle" data-id='${e.articleId}'><span class="text"><span>▤</span> ${e.title}</span><span
                            class="time">${e.publishTime}</span></div>`
        htmlStr += domStr
    })
    if (!data || !data.length) {
        articleInfoList.innerHTML = "<div class='noData'>暂无相关资讯</div>"
    } else {
        articleInfoList.innerHTML = htmlStr
    }
    var pagercontainer = document.getElementById('pagercontainer');
    if (data.length) {
        console.log(Math.ceil(data.length / 10))
        createPager(articlePage, Math.ceil(articleList.length / 10), 5, pagercontainer);
        pagercontainer.style.display = 'block';
    } else {
        pagercontainer.style.display = 'none';
    }
}
function addClickEvent() {
    let noticeInfoList = document.querySelectorAll('.jumpArticle');
    // console.log(noticeInfoList)
    Array.from(noticeInfoList).forEach((e, index) => {
        if (!e.getAttribute('data-event')) {
            e.addEventListener("click", function () {
                articleQuery(e)
            });
            e.setAttribute('data-event', 1);
            // console.log(e)
        }
    })
}
function setArticleData(data) {
    document.getElementById('contact').style.display = 'none';
    document.getElementById('articleContent').style.display = 'block';
    let domStr = ''
    // domStr = `<div class="title redTitle">
    //         <div class="label" style="font-size:${data.titleSize}">${data.redHeadContent}</div>
    //         <div class="operator centeroperator redHeadNumber">
    //         ${data.redHeadNumber}
    //         </div>
    //         <div class="redHeadTitle">${data.title}</div>
    //     </div>
    //     <div class="contentText">`+ data.content + `</div>`
    if (data.whetherRedHead) {
        domStr = `<div class="title redTitle">
                <div class="label" style="font-size:${data.titleSize}">${data.redHeadContent}</div>
                <div class="operator centeroperator redHeadNumber">
                ${data.redHeadNumber}
                </div>
                <div class="redHeadTitle">${data.title}</div>
            </div>
            <div class="contentText">`+ data.content + `</div>`
    } else {
        domStr = `<div class="title">
                <div class="label" style="font-size:${data.titleSize}">${data.title}</div>
                <div class="operator centeroperator">
                    <span>文章来源：${data.operator}</span>
                    <span>${data.publishTime} </span>
                    <span class="viewVolume">浏览${data.viewVolume}次</span>
                </div>
            </div>
            <div class="contentText">`+ data.content + `</div>`
    }

    document.getElementById('articleContent').innerHTML = domStr

}
function articleQuery(e) {
    var id = e.getAttribute('data-id')
    var url = e.getAttribute('data-url')
    if (id) {
        ajax('GET', `portalWebsite/article/query?articleId=${id}`, null, function (res) {
            let { data } = res;
            if (data.jumpType == 'URL' && data.url) {
                jumpArticle(data)
            } else {
                setArticleData(data)
            }
        })
    } else {
        window.open(url, '_blank')
    }

}
//获取nav
function queryHomepageNavigation() {
    ajax('GET', 'portalWebsite/homepage/queryHomepageNavigation', null, function (res) {
        var { data } = res
        var tagList = document.getElementById('tagList');
        var children = Array.from(tagList.children)
        var tagList_start = children[0];
        var tagList_end = children[children.length - 1];
        tagList.appendChild(tagList_start);
        navList = data || []
        console.log(navList)
        navList.forEach(e => {
            var newDiv = document.createElement('div');
            newDiv.textContent = e.navigationName;
            newDiv.className = 'tag tagBtn newTag'
            tagList.appendChild(newDiv);
        });
        tagList.appendChild(tagList_end)
        var newTagList = document.querySelectorAll('.newTag');
        Array.from(newTagList).forEach((e, index) => {
            console.log()
            e.addEventListener("click", function () {
                if (navList[index].functionType == 'URL') {
                    window.open(navList[index].url)
                } else {
                    queryByNavigationId(data[index].navigationId)
                }
            });
        })
        setNavHoverColor(newTagList)
    })
}
//后去页面基本数据（背景图自定义按钮颜色）
function queryEndPage() {
    document.getElementById('nav').style.backgroundColor = sessionStorage.navigationColor || '#164fa6';
    document.getElementById('footer').style.backgroundColor = sessionStorage.navigationColor || '#164fa6';
    ajax('GET', 'portalWebsite/homepage/queryEndPage', null, function (res) {
        endData = res.data || {}
        var backgroundImageUrl = `${$baseUrl.fileServiceUrl}portalWebsite/files/download?fileId=${endData.backgroundImage}`
        var headerImageUrl = `${$baseUrl.fileServiceUrl}portalWebsite/files/download?fileId=${endData.headerImage}`
        var navigationColor = endData.navigationColor || '#164fa6'
        var hoverColor = endData.hoverColor || '#137bff'
        endData.backgroundImage && (document.getElementById('homePage').style.backgroundImage = `url(${backgroundImageUrl})`);
        endData.headerImage && (document.getElementById('homePageLogo').src = headerImageUrl);
        document.getElementById('nav').style.backgroundColor = navigationColor;
        document.getElementById('footer').style.backgroundColor = navigationColor;
        document.getElementById('headerName').innerHTML = endData.headerName || '';
        document.getElementById('organizer').innerHTML = endData.organizer || '';
        document.getElementById('phoneNumber').innerHTML = endData.phoneNumber || '';
        document.getElementById('address').innerHTML = endData.address || '';
        document.getElementsByTagName("title")[0].textContent = endData.headerName || '公安官网';
        sessionStorage.setItem('hoverColor', hoverColor);
        sessionStorage.setItem('navigationColor', navigationColor);
    })
}

//获取时间
function getNowTime() {
    timer = setInterval(() => {
        document.getElementById('newTime').innerHTML = formatTime(new Date())
    }, 999);
};